<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DEM高程计算器 - 线段最高点分析</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #4CAF50;
        }
        .container {
            background-color: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .input-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            box-sizing: border-box;
        }
        .input-row {
            display: flex;
            gap: 15px;
        }
        .input-row .input-group {
            flex: 1;
            margin-bottom: 0;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button:active {
            background-color: #3d8b40;
        }
        .results {
            margin-top: 30px;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 4px;
            border-left: 4px solid #4CAF50;
        }
        .results h2 {
            margin-top: 0;
            color: #333;
        }
        .result-item {
            margin-bottom: 10px;
            padding: 10px;
            background-color: white;
            border-radius: 4px;
            border: 1px solid #eee;
        }
        .status {
            margin-top: 20px;
            padding: 15px;
            background-color: #e3f2fd;
            border-radius: 4px;
            font-style: italic;
            color: #1565c0;
        }
        .error {
            background-color: #ffebee;
            color: #c62828;
            border-left-color: #f44336;
        }
        .success {
            background-color: #e8f5e9;
            color: #2e7d32;
            border-left-color: #4caf50;
        }

        .highest-point-container {
            margin-top: 40px;
            padding: 30px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .highest-point-result {
            font-size: 18px;
            line-height: 1.6;
        }

        .highest-point-result strong {
            color: #4CAF50;
        }

        .separator {
            margin: 40px 0;
            height: 2px;
            background-color: #e0e0e0;
        }
        .test-section {
            margin-top: 30px;
            padding: 20px;
            background-color: #fff3e0;
            border-radius: 4px;
            border-left: 4px solid #ff9800;
        }
        .test-section h2 {
            color: #e65100;
            margin-top: 0;
        }
        .test-results {
            margin-top: 15px;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4CAF50;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .instructions {
            margin-top: 30px;
            padding: 20px;
            background-color: #f5f5f5;
            border-radius: 4px;
            font-size: 14px;
            color: #666;
        }
        .instructions h3 {
            margin-top: 0;
            color: #555;
        }
    </style>
</head>
<body>
    <h1>DEM高程计算器</h1>
    
    <div class="container">
        <!-- 输入区域 -->
        <div class="input-row">
            <div class="input-group">
                <label for="longitude">经度:</label>
                <input type="number" id="longitude" step="0.0001" placeholder="例如: 104.06">
            </div>
            <div class="input-group">
                <label for="latitude">纬度:</label>
                <input type="number" id="latitude" step="0.0001" placeholder="例如: 30.67">
            </div>
        </div>
        
        <button id="calculateBtn">计算高程</button>
        
        <!-- 加载状态 -->
        <div id="status" class="status">
            等待数据加载... <span id="loadingIndicator" class="loading"></span>
        </div>
        
        <!-- 计算结果 -->
        <div id="results" class="results" style="display: none;">
            <h2>计算结果</h2>
            <div id="resultContent" class="result-item">
                <!-- 结果将在这里显示 -->
            </div>
        </div>
        
        <!-- 自动测试区域 -->
        <div class="test-section">
            <h2>自动测试结果</h2>
            <div id="testResults" class="test-results">
                <!-- 自动测试结果将在这里显示 -->
            </div>
        </div>
    </div>
    
    <!-- 使用说明 -->
    <div class="instructions">
        <h3>使用说明</h3>
        <ul>
            <li>输入经度和纬度值，点击"计算高程"按钮获取该点的高程数据</li>
            <li>页面加载时会自动测试预设点（成都市和西安市）的高程值</li>
            <li>DEM数据文件较大，加载可能需要一些时间</li>
            <li>若输入的坐标不在数据范围内，将会显示错误提示</li>
            <li>若查询点周围数据无效，将使用有效点的平均值或返回0</li>
        </ul>
    </div>
    
    <script src="dem_reader.js"></script>
    <script>
        // 创建DEM读取器实例
        const demReader = new DemReader();
        
        // DOM元素
        const longitudeInput = document.getElementById('longitude');
        const latitudeInput = document.getElementById('latitude');
        const calculateBtn = document.getElementById('calculateBtn');
        const resultsDiv = document.getElementById('results');
        const resultContent = document.getElementById('resultContent');
        const statusDiv = document.getElementById('status');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const testResultsDiv = document.getElementById('testResults');
        
        // 更新状态显示
        function updateStatus(message, isError = false, isSuccess = false) {
            statusDiv.textContent = message;
            statusDiv.className = 'status';
            
            if (isError) {
                statusDiv.classList.add('error');
            } else if (isSuccess) {
                statusDiv.classList.add('success');
            }
            
            loadingIndicator.style.display = isError || isSuccess ? 'none' : 'inline-block';
        }
        
        // 添加测试结果
        function addTestResult(location, longitude, latitude, elevation) {
            const resultItem = document.createElement('div');
            resultItem.className = 'result-item';
            resultItem.innerHTML = `
                <strong>${location}:</strong><br>
                坐标: (${longitude.toFixed(6)}, ${latitude.toFixed(6)})<br>
                高程: ${elevation.toFixed(3)} 米
            `;
            testResultsDiv.appendChild(resultItem);
        }
        
        // 执行自动测试
        async function runAutoTests() {
            // 预设测试点 - 覆盖不同地形特征
            const testPoints = [
                { location: '成都市', longitude: 104.055, latitude: 30.6735 }, // 四川盆地
                { location: '西安市', longitude: 108.978, latitude: 34.3012 }  // 关中平原
            ];
            
            for (const point of testPoints) {
                const elevation = demReader.calculateElevation(point.longitude, point.latitude);
                addTestResult(point.location, point.longitude, point.latitude, elevation);
            }
        }
        
        // 计算高程处理函数
        function handleCalculateElevation() {
            const longitude = parseFloat(longitudeInput.value);
            const latitude = parseFloat(latitudeInput.value);
            
            // 验证输入
            if (isNaN(longitude) || isNaN(latitude)) {
                resultContent.innerHTML = '<span style="color: red;">请输入有效的经纬度值</span>';
                resultsDiv.style.display = 'block';
                return;
            }
            
            // 计算高程
            const elevation = demReader.calculateElevation(longitude, latitude);
            
            // 显示结果
            resultContent.innerHTML = `
                <strong>查询结果:</strong><br>
                经度: ${longitude.toFixed(6)}<br>
                纬度: ${latitude.toFixed(6)}<br>
                高程: ${elevation.toFixed(3)} 米
            `;
            resultsDiv.style.display = 'block';
        }
        
        // 加载DEM数据
        async function loadDemData() {
            try {
                updateStatus('正在加载DEM数据，请稍候...');
                
                // 已将DEM数据文件复制到当前目录，避免浏览器跨域访问问题
                const success = await demReader.loadDemData('dem001.txt');
                
                if (success) {
                    updateStatus('DEM数据加载成功，可以开始计算高程', false, true);
                    
                    // 执行自动测试
                    await runAutoTests();
                } else {
                    updateStatus('DEM数据加载失败', true);
                }
            } catch (error) {
                updateStatus(`加载数据时发生错误: ${error.message}`, true);
            }
        }
        
        // 事件监听器
        calculateBtn.addEventListener('click', handleCalculateElevation);
        
        // 为输入框添加回车事件
        longitudeInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                latitudeInput.focus();
            }
        });
        
        latitudeInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                handleCalculateElevation();
            }
        });
        
        // 页面加载完成后加载DEM数据
        document.addEventListener('DOMContentLoaded', loadDemData);
    </script>

    <div class="separator"></div>

    <!-- 线段最高点分析器 -->
    <div class="highest-point-container">
        <h2>线段最高点分析</h2>
        <p>输入两个点的经纬度，计算它们连线两侧25公里范围内的最高点信息。</p>
        
        <div class="input-group">
            <h3>起点</h3>
            <div class="input-row">
                <div class="input-group">
                    <label for="start-latitude">纬度</label>
                    <input type="number" id="start-latitude" step="0.000001" placeholder="例如：39.9042">
                </div>
                <div class="input-group">
                    <label for="start-longitude">经度</label>
                    <input type="number" id="start-longitude" step="0.000001" placeholder="例如：116.4074">
                </div>
            </div>
        </div>

        <div class="input-group">
            <h3>终点</h3>
            <div class="input-row">
                <div class="input-group">
                    <label for="end-latitude">纬度</label>
                    <input type="number" id="end-latitude" step="0.000001" placeholder="例如：39.9416">
                </div>
                <div class="input-group">
                    <label for="end-longitude">经度</label>
                    <input type="number" id="end-longitude" step="0.000001" placeholder="例如：116.4663">
                </div>
            </div>
        </div>

        <button id="find-highest-point-btn">查找最高点</button>

        <div class="results" id="highest-point-results">
            <h3>最高点结果</h3>
            <div class="highest-point-result" id="highest-point-info">
                请输入两个点的坐标并点击按钮开始分析。
            </div>
        </div>
    </div>

    <script src="line_highest_point.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化DEM读取器和线段分析器
            const analyzerDemReader = new DemReader();
            const lineAnalyzer = new LineHighestPointAnalyzer(analyzerDemReader);
            
            // 加载DEM数据用于线段分析
            async function loadAnalyzerDemData() {
                const statusElement = document.getElementById('highest-point-info');
                statusElement.innerHTML = '正在加载DEM数据...';
                
                try {
                    const success = await analyzerDemReader.loadDemData('dem001.txt');
                    if (success) {
                        statusElement.innerHTML = 'DEM数据加载成功，可以开始分析。';
                        statusElement.classList.add('success');
                    } else {
                        statusElement.innerHTML = 'DEM数据加载失败，请检查文件路径是否正确。';
                        statusElement.classList.add('error');
                    }
                } catch (error) {
                    statusElement.innerHTML = '加载DEM数据时发生错误：' + error.message;
                    statusElement.classList.add('error');
                    console.error(error);
                }
            }
            
            // 加载DEM数据
            loadAnalyzerDemData();
            
            // 查找最高点的点击事件
            document.getElementById('find-highest-point-btn').addEventListener('click', async function() {
                const startLat = parseFloat(document.getElementById('start-latitude').value);
                const startLon = parseFloat(document.getElementById('start-longitude').value);
                const endLat = parseFloat(document.getElementById('end-latitude').value);
                const endLon = parseFloat(document.getElementById('end-longitude').value);
                
                const statusElement = document.getElementById('highest-point-info');
                
                // 验证输入
                if (isNaN(startLat) || isNaN(startLon) || isNaN(endLat) || isNaN(endLon)) {
                    statusElement.innerHTML = '请输入有效的经纬度坐标。';
                    statusElement.classList.remove('success');
                    statusElement.classList.add('error');
                    return;
                }
                
                // 检查DEM数据是否已加载
                if (!analyzerDemReader.dataLoaded) {
                    statusElement.innerHTML = 'DEM数据尚未加载完成，请稍候...';
                    statusElement.classList.remove('success');
                    statusElement.classList.add('error');
                    return;
                }
                
                // 显示加载状态
                statusElement.innerHTML = '正在分析最高点...这可能需要一些时间，请耐心等待。';
                statusElement.classList.remove('success', 'error');
                
                try {
                    // 开始测量性能
                    const startTime = performance.now();
                    
                    // 查找最高点
                    const highestPoint = lineAnalyzer.findHighestPoint(startLat, startLon, endLat, endLon, 25);
                    
                    // 计算耗时
                    const endTime = performance.now();
                    const elapsedTime = (endTime - startTime).toFixed(2);
                    
                    if (highestPoint) {
                        statusElement.innerHTML = 
                            `分析完成 (耗时: ${elapsedTime}ms)<br><br>` +
                            `找到最高点：<br>` +
                            `<strong>纬度：</strong>${highestPoint.latitude.toFixed(6)}<br>` +
                            `<strong>经度：</strong>${highestPoint.longitude.toFixed(6)}<br>` +
                            `<strong>高程：</strong>${highestPoint.elevation.toFixed(2)} 米`;
                        statusElement.classList.add('success');
                        statusElement.classList.remove('error');
                    } else {
                        statusElement.innerHTML = '未能找到有效最高点，请检查输入坐标是否在DEM数据范围内。';
                        statusElement.classList.remove('success');
                        statusElement.classList.add('error');
                    }
                } catch (error) {
                    statusElement.innerHTML = '分析过程中发生错误：' + error.message;
                    statusElement.classList.remove('success');
                    statusElement.classList.add('error');
                    console.error(error);
                }
            });
        });
    </script>
</body>
</html>